//
//  CoreData.m
//  Pianke
//
//  Created by 黄俊杰 on 16/1/5.
//  Copyright © 2016年 dada. All rights reserved.
//

#import "CoreData.h"

@implementation CoreData

+(NSMutableArray *)selectData:(NSInteger)key{

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Radio" inManagedObjectContext:[[CoreDataManager shareManager] managedObjectContext]];
    [fetchRequest setEntity:entity];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"uname"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [[[CoreDataManager shareManager] managedObjectContext] executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@",error);
    }
    
    if (key == 0) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:fetchedObjects];
        return array;
    }else{
    
        NSMutableArray *musicArray = [NSMutableArray array];
        for (Radio *radio in fetchedObjects) {
            
            [musicArray addObject:radio.musicUrl];
        }
        return musicArray;
    }
}

+(void)deleteData:(NSString *)musicUrl{

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Radio" inManagedObjectContext:[[CoreDataManager shareManager] managedObjectContext]];
    [fetchRequest setEntity:entity];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"uname"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [[[CoreDataManager shareManager] managedObjectContext] executeFetchRequest:fetchRequest error:&error];
    NSMutableArray *array = [NSMutableArray arrayWithArray:fetchedObjects];
    for (Radio *radio in array) {
        if ([radio.musicUrl isEqualToString:musicUrl]) {
            
            [[[CoreDataManager shareManager] managedObjectContext] deleteObject:radio];
            [[CoreDataManager shareManager] saveContext];
        }
    }
}

+(void)insertData:(Radio *)radio{

    Radio *radioDB = [NSEntityDescription insertNewObjectForEntityForName:@"Radio" inManagedObjectContext:[[CoreDataManager shareManager] managedObjectContext]];
    radioDB.webview_url = radio.webview_url;
    radioDB.musicUrl = radio.musicUrl;
    radioDB.title = radio.title;
    radioDB.uname = radio.uname;
    radioDB.coverimg = radio.coverimg;
    [[CoreDataManager shareManager] saveContext];
}

@end
